package org.jeecg.modules.gwcjava.jiekou.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.google.gson.Gson;
import com.google.gson.JsonElement;
import io.swagger.annotations.Api;
import lombok.extern.slf4j.Slf4j;
import net.sf.json.JSONObject;
import org.jeecg.modules.gwcjava.jiekou.entity.*;
import org.jeecg.modules.gwcjava.jiekou.service.BusinessLogicService;
import org.jeecg.modules.gwcjava.jiekou.service.MlccUserInfoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.text.DecimalFormat;
import java.util.List;
import java.util.Random;

/**
 * 前端接口处理
 * */
@Api(tags="web端接口")
@RestController
@RequestMapping("/goods/cart/interface")
@Slf4j
public class GoodsCartController {
    @Autowired
    private BusinessLogicService logicService;
    /**查询用户信息*/
    @Autowired
    private MlccUserInfoService userservice;


    /**
     * 现货加入购物车
     * @return
     */
    @PostMapping(value = "/add_goods_cart")
    @Transactional(rollbackFor = Exception.class)
    public JSONObject add_goods_cart(String jsondata, String goods_id, String sumbuy, String sumMoney, String token){
        JSONObject obj = new JSONObject();//返回对象
        Gson gson = new Gson();
//        System.out.println("==="+jsondata);
        try {
            MlccUserInfo userInfo = userservice.queryUserinfoByusername(token, 3);
            if (userInfo == null) {
                obj.put("code", 4);
                obj.put("msg", "token已失效，请重新登录");
                return obj;
            }
            int code1 = 0,code2 = 0;
            //判断购物车里是否有该商品
            ThirdCartInfo cartInfo1 = logicService.query_cartinfoBygoodId(goods_id,userInfo.getId().toString());
            if(cartInfo1!=null){//该购物车里面有该商品
                if(jsondata!=null && !"".equals(jsondata)){//说明有规格
                    //声明最终价格
                    String lost_price = "0.00";
                    double sumprice = 0.00;
                    DecimalFormat df = new DecimalFormat("0.00");
                    //获取原来的商品总数
                    double oldnum = Double.parseDouble(cartInfo1.getGoodsNum());
                    //声明新增的数量
                    double newinsertNum = 0.0;
                    //获取现在的商品数量
                    JSONArray jsonArray = JSON.parseArray(jsondata);
                    for(int i=0;i<jsonArray.size();i++){
                        System.out.println(jsonArray.get(i).toString());
                        JsonCartBuyNum hPolicyTypeDictDto = gson.fromJson(jsonArray.get(i).toString(), JsonCartBuyNum.class);
                        System.out.println("json数据的值=="+hPolicyTypeDictDto.getBuyNum());
                        if(Double.parseDouble(hPolicyTypeDictDto.getBuyNum())>0){
                            newinsertNum+=Double.parseDouble(hPolicyTypeDictDto.getBuyNum());
                            //循环执行修改规格里面的数量
                            ThirdCartInfo cartbuyNum = logicService.query_cartinfobuyNum_BygoodId(goods_id,hPolicyTypeDictDto.getGoodsSpecificationsId(),hPolicyTypeDictDto.getGoodsSizeId(),userInfo.getId().toString());
                            if(cartbuyNum!=null){
                                double num1 = Double.parseDouble(cartbuyNum.getBuyNum());
                                code2 = logicService.update_cart_goods_buynum(cartbuyNum.getId(),(Double.parseDouble(hPolicyTypeDictDto.getBuyNum())+num1)+"");
                            }else {
                                int random2=new Random().nextInt(100000)+1;//为变量赋随机值1-99999999;
                                Long startTs2 = System.currentTimeMillis(); // 当前时间戳
                                ThirdCartInfo cart_buydata = new ThirdCartInfo();
                                cart_buydata.setId(startTs2.toString()+random2+i);
                                cart_buydata.setGoodsId(goods_id);
                                cart_buydata.setGoodsCartId(cartInfo1.getId());
                                cart_buydata.setGoodsSpecificationsId(hPolicyTypeDictDto.getGoodsSpecificationsId());
                                cart_buydata.setGoodsSizeId(hPolicyTypeDictDto.getGoodsSizeId());
                                cart_buydata.setKucunBathId(hPolicyTypeDictDto.getKucunBathId());
                                cart_buydata.setUserId(userInfo.getId().toString());
                                cart_buydata.setBuyNum(hPolicyTypeDictDto.getBuyNum());
                                cart_buydata.setCreateBy(userInfo.getUsername());
                                //添加购物车下的购买数量
                                code2 = logicService.add_cart_goods_buynum(cart_buydata);
                            }
                        }
                    }
                    //现在的总数
                    double nowsum = oldnum+newinsertNum;
                    //查询商品详情
                    ThirdGoodsInfo goodsinfo = logicService.query_goodsDetailByid(goods_id);
                    if(goodsinfo.getIsMain()==0){
                        //根据系列id查询价格区间
                        List<ThirdGoodsLadderPrice> datalist = logicService.query_rungpricedatalist(goodsinfo.getGoodsSeriesId());
                        if(datalist.size()>0) {
                            for (int i = 0; i < datalist.size(); i++) {
                                if (Double.parseDouble(datalist.get(i).getMin()) <= nowsum && Double.parseDouble(datalist.get(i).getMax()) >= nowsum) {
                                    sumprice = Double.parseDouble(datalist.get(i).getPrice()) * nowsum;
                                    break;
                                }
                            }
                            lost_price = df.format(sumprice);
                        }
                    }else {
                        sumprice = Double.parseDouble(goodsinfo.getPrice()) * nowsum;
                        lost_price = df.format(sumprice);
                    }
                    //直接修改商品总数
                    code1 = logicService.update_cart_goods(cartInfo1.getId(),nowsum+"",lost_price);
                }else {
                    //声明最终价格
                    String lost_price = "0.00";
                    double sumprice = 0.00;
                    DecimalFormat df = new DecimalFormat("0.00");
                    //获取原来的商品总数
                    double oldnum = Double.parseDouble(cartInfo1.getGoodsNum());
                    double nowsum = oldnum+1;
//                    double nowsum = 1;
                    //查询商品详情
                    ThirdGoodsInfo goodsinfo = logicService.query_goodsDetailByid(goods_id);
                    if(goodsinfo.getIsMain()==0){
                        //根据系列id查询价格区间
                        List<ThirdGoodsLadderPrice> datalist = logicService.query_rungpricedatalist(goodsinfo.getGoodsSeriesId());
                        if(datalist.size()>0) {
                            for (int i = 0; i < datalist.size(); i++) {
                                if (Double.parseDouble(datalist.get(i).getMin()) <= nowsum && Double.parseDouble(datalist.get(i).getMax()) >= nowsum) {
                                    sumprice = Double.parseDouble(datalist.get(i).getPrice()) * nowsum;
                                    break;
                                }
                            }
                            lost_price = df.format(sumprice);
                        }
                    }else {
                        sumprice = Double.parseDouble(goodsinfo.getPrice()) * nowsum;
                        lost_price = df.format(sumprice);
                    }
                    //直接修改商品总数
                    code1 = logicService.update_cart_goods(cartInfo1.getId(),nowsum+"",lost_price);
                }
            }else {
                Long startTs = System.currentTimeMillis(); // 当前时间戳
                //8位随机数
                int random=new Random().nextInt(100000)+1;//为变量赋随机值1-99999999;
                String cartId = "CART"+startTs.toString()+random;
                //插入购物车
                ThirdCartInfo addcart_data = new ThirdCartInfo();
                addcart_data.setId(cartId);
                addcart_data.setSumMoney(sumMoney);
                addcart_data.setGoodsNum(sumbuy);
                addcart_data.setUserId(userInfo.getId().toString());
                addcart_data.setSysOrgCode(userInfo.getOrgCode());
                addcart_data.setGoodsId(goods_id);
                addcart_data.setCreateBy(userInfo.getUsername());
                code1 = logicService.add_cart_goods(addcart_data);
                System.out.println("加入购物车=="+code1);
                if(jsondata!=null && !"".equals(jsondata)){
                    //方法2、使用JSONArray
                    JSONArray jsonArray = JSON.parseArray(jsondata);
                    for(int i=0;i<jsonArray.size();i++){
//                    System.out.println("json数据的大小=="+jsonArray.size()+"==");
                        System.out.println(jsonArray.get(i).toString());
                        JsonCartBuyNum hPolicyTypeDictDto = gson.fromJson(jsonArray.get(i).toString(), JsonCartBuyNum.class);
//                    System.out.println("json数据的值=="+hPolicyTypeDictDto.getGoodsId());
                        if(Double.parseDouble(hPolicyTypeDictDto.getBuyNum())>0){
                            int random2=new Random().nextInt(100000)+1;//为变量赋随机值1-99999999;
                            Long startTs2 = System.currentTimeMillis(); // 当前时间戳
                            ThirdCartInfo cart_buydata = new ThirdCartInfo();
                            cart_buydata.setId(startTs2.toString()+random2+i);
                            cart_buydata.setGoodsId(goods_id);
                            cart_buydata.setGoodsCartId(cartId);
                            cart_buydata.setGoodsSpecificationsId(hPolicyTypeDictDto.getGoodsSpecificationsId());
                            cart_buydata.setGoodsSizeId(hPolicyTypeDictDto.getGoodsSizeId());
                            cart_buydata.setKucunBathId(hPolicyTypeDictDto.getKucunBathId());
                            cart_buydata.setUserId(userInfo.getId().toString());
                            cart_buydata.setBuyNum(hPolicyTypeDictDto.getBuyNum());
                            cart_buydata.setCreateBy(userInfo.getUsername());
                            //添加购物车下的购买数量
                            code2 = logicService.add_cart_goods_buynum(cart_buydata);
                        }
                    }
                }
            }
            if(code1>0 || code2>0){
                obj.put("code", 0);
                obj.put("msg", "加入购物车成功！");
            }else {
                obj.put("code", 1);
                obj.put("msg", "加入购物车失败");
            }
            return obj;
        }catch (Exception e){
            //手动回滚事务
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            obj.put("code", 2);
            obj.put("msg", "加入购物车失败");
            return obj;
        }
    }

}
